import { constantRoutes } from '@/router'
import { getMenus } from '@/api/login'

const permission = {
  state: {
    routes: [], // 动态路由
    addRoutes: [],  // 在静态路由的基础上追加动态路由
    currentRoutes: {} // 当前选中父级路由的子路由
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = constantRoutes.concat(routes)
      state.routes = constantRoutes[0].children.concat(routes)
    },
    SET_CURRENT_ROUTES: (state, routes) => {
      state.currentRoutes = routes
    }
  },
  actions: {
    // 生成路由
    GenerateMenus({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getMenus().then(res => {
          const accessedRoutes = filterAsyncRouter(res.data.data)
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
        route.component = loadView(route.component)
    }
    if (route.children != null && route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

// 新路由
export const loadView = (view) => {
  console.log('loadView', view)
  return (resolve) => require([`@/views/${view}`], resolve)
};

export default permission
